package com.fulihui.wgj.admin.integration.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.fulihui.common.builder.web.JsonResultBuilder;
import com.fulihui.common.builder.web.PageViewBuilder;
import com.fulihui.common.conv.BeanConv;
import com.fulihui.common.error.Errors;
import com.fulihui.common.request.rpc.AppRequest;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.result.rpc.SimpleResult;
import com.fulihui.common.result.web.PageView;
import com.fulihui.common.result.web.Result;
import com.fulihui.common.util.DateUtils;
import com.fulihui.common.util.RpcResultCheckUtil;
import com.fulihui.weixinsdk.model.Article;
import com.fulihui.weixinsdk.model.NewsMessage;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsCalcRequest;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsCancelRequest;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsLogPageRequest;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsQueryRequest;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsSendPreRequest;
import com.fulihui.wgj.admin.api.wx48.request.Wx48NewsSendRequest;
import com.fulihui.wgj.admin.api.wx48.vo.Wx48NewsInfo;
import com.fulihui.wgj.admin.api.wx48.vo.Wx48NewsInfoVO;
import com.fulihui.wgj.admin.api.wx48.vo.Wx48NewsLogVO;
import com.fulihui.wgj.admin.config.properties.AdminProperties;
import com.fulihui.wgj.admin.integration.Wx48NewsServiceClient;
import com.fulihui.wgj.facade.dto.Wx48NewsInfoDTO;
import com.fulihui.wgj.facade.dto.Wx48NewsLogDTO;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsCrowdRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsInfoPageQueryRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsInfoSaveRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsLogCancelRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsLogPageQueryRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsLogSaveRequest;
import com.fulihui.wgj.facade.request.wx48.WxUserInfoSendSingle48HRequest;
import com.fulihui.wgj.facade.result.wx48.Wx48NewsInfoPageResult;
import com.fulihui.wgj.facade.result.wx48.Wx48NewsLogPageResult;
import com.fulihui.wgj.facade.service.wx48.Wx48NewsInfoService;
import com.fulihui.wgj.facade.service.wxuser.WxUserInfoService;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.List;
import java.util.Objects;

/**
 * @author: Levon
 * @date: 2018-07-19 14:47
 */
@Service
public class Wx48NewsServiceClientImpl implements Wx48NewsServiceClient {

    private final static Logger LOGGER = LoggerFactory.getLogger(Wx48NewsServiceClientImpl.class);

    @Reference(version = "1.0.0")
    private Wx48NewsInfoService wx48NewsInfoService;

    @Reference(version = "1.0.0")
    private WxUserInfoService wxUserInfoService;

    @Autowired
    private AdminProperties adminProperties;

    @Override
    public Result<Long> saveNews(Wx48NewsInfoSaveRequest request) {
        SimpleResult<Long> baseResult = wx48NewsInfoService.saveNewsInfo(request);
        if (RpcResultCheckUtil.isSuccess(baseResult)) {
            return JsonResultBuilder.succ(baseResult.getData());
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }

    @Override
    public PageView<Wx48NewsInfoVO> queryPage(Wx48NewsQueryRequest request) {

        List<Wx48NewsInfoVO> vos = Lists.newArrayList();

        Wx48NewsInfoPageQueryRequest queryRequest = new Wx48NewsInfoPageQueryRequest();
        queryRequest.setAppId(request.getAppId());
        queryRequest.setPage(request.getPage());
        queryRequest.setRows(request.getRows());
        queryRequest.setTitle(request.getTitle());
        queryRequest.setUseType(request.getUseType());
        Wx48NewsInfoPageResult pageResult = wx48NewsInfoService.pageQueryNewsInfo(queryRequest);
        if (RpcResultCheckUtil.isSuccess(pageResult)) {
            List<Wx48NewsInfoDTO> values = pageResult.getValue();
            if (!CollectionUtils.isEmpty(values)) {
                for (Wx48NewsInfoDTO value : values) {

                    Wx48NewsInfoVO infoVO = new Wx48NewsInfoVO();
                    infoVO.setId(value.getId());
                    String xmlContent = value.getXmlContent();
                    NewsMessage newsMessage = JSON.parseObject(xmlContent, NewsMessage.class);
                    NewsMessage.News news = newsMessage.getNews();
                    List<Article> articles = news.getArticles();

                    List<Wx48NewsInfo> newsInfos = Lists.newArrayList();
                    if (!CollectionUtils.isEmpty(articles)) {
                        for (Article article : articles) {
                            Wx48NewsInfo newsInfo = new Wx48NewsInfo();
                            newsInfo.setTitle(article.getTitle());
                            newsInfo.setImgurl(adminProperties.getImgproxy() + article.getPicurl());
                            newsInfo.setUrl(article.getUrl());
                            newsInfo.setGmtCreate(DateUtils.formatNoSecondFormat(value.getGmtCreate()));
                            newsInfo.setGmtModified(DateUtils.formatNoSecondFormat(value.getGmtModified()));
                            newsInfos.add(newsInfo);
                        }
                    }
                    infoVO.setNewsInfos(newsInfos);
                    vos.add(infoVO);
                }
            }
        }
        return PageViewBuilder.build(vos, pageResult.getPage(), pageResult.getRows(), pageResult.getTotalRows());
    }

    @Override
    public Result<String> sendSalc(Wx48NewsCalcRequest request) {
        Wx48NewsCrowdRequest crowdRequest = BeanConv.copy(request, Wx48NewsCrowdRequest.class);
        crowdRequest.setAppId(request.getAppId());
        try {
            if (Objects.nonNull(request.getSubscribeTimeStart())) {
                crowdRequest.setSubscribeTimeStart(DateUtils.parseNewFormat(request.getSubscribeTimeStart()));
            }
            if (Objects.nonNull(request.getSubscribeTimeEnd())) {
                crowdRequest.setSubscribeTimeEnd(DateUtils.parseNewFormat(request.getSubscribeTimeEnd()));
            }
        } catch (ParseException e) {
            return JsonResultBuilder.fail(Errors.Commons.SYSTEM_ERROR.getErrcode(), e.getMessage());
        }
        SimpleResult<String> simpleResult = wx48NewsInfoService.countSendWx48News(crowdRequest);
        if (RpcResultCheckUtil.isSuccess(simpleResult)) {
            return JsonResultBuilder.succ(simpleResult.getData());
        }
        return JsonResultBuilder.fail(simpleResult.getErrcode(), simpleResult.getErrmsg());
    }

    @Override
    public Result<Boolean> send(Wx48NewsSendRequest request) {

        Wx48NewsLogSaveRequest logSaveRequest = new Wx48NewsLogSaveRequest();
        logSaveRequest.setAppId(request.getAppId());
        if (!StringUtils.isEmpty(request.getJobTime())) {
            try {
                logSaveRequest.setJobTime(DateUtils.parseNewFormat(request.getJobTime()));
            } catch (ParseException e) {
                LOGGER.error("发送模板消息，时间解析失败。", e);
            }
        }
        Wx48NewsCrowdRequest crowdRequest = BeanConv.copy(request, Wx48NewsCrowdRequest.class);
        try {
            if (Objects.nonNull(request.getSubscribeTimeStart())) {
                crowdRequest.setSubscribeTimeStart(DateUtils.parseNewFormat(request.getSubscribeTimeStart()));
            }
            if (Objects.nonNull(request.getSubscribeTimeEnd())) {
                crowdRequest.setSubscribeTimeEnd(DateUtils.parseNewFormat(request.getSubscribeTimeEnd()));
            }
        } catch (ParseException e) {
            return JsonResultBuilder.fail(Errors.Commons.SYSTEM_ERROR.getErrcode(), e.getMessage());
        }
        crowdRequest.setAppId(request.getAppId());
        logSaveRequest.setWx48NewsCrowdRequest(crowdRequest);
        logSaveRequest.setNewsId(request.getNewsId());
        logSaveRequest.setName(request.getName());
        logSaveRequest.setSendConditionDesc(request.getSendConditionDesc());
        BaseResult baseResult = wx48NewsInfoService.sendWx48News(logSaveRequest);
        if (RpcResultCheckUtil.isSuccess(baseResult)) {
            return JsonResultBuilder.succ(true);
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }

    @Override
    public PageView<Wx48NewsLogVO> queryNewsLogPage(Wx48NewsLogPageRequest request) {

        List<Wx48NewsLogVO> logVOS = Lists.newArrayList();

        Wx48NewsLogPageQueryRequest queryRequest = new Wx48NewsLogPageQueryRequest();
        queryRequest.setAppId(request.getAppId());
        try {
            queryRequest.setEndTime(DateUtils.parseWebFormat(request.getEndTime()));
            queryRequest.setStartTime(DateUtils.parseWebFormat(request.getStartTime()));
        } catch (ParseException e) {
            LOGGER.error("查询模板消息发送记录，时间解析失败。", e);
        }
        queryRequest.setName(request.getName());
        queryRequest.setStatus(request.getStatus());
        queryRequest.setPage(request.getPage());
        queryRequest.setRows(request.getRows());
        Wx48NewsLogPageResult pageResult = wx48NewsInfoService.pageQueryNewsLog(queryRequest);
        if (RpcResultCheckUtil.isSuccess(pageResult)) {
            List<Wx48NewsLogDTO> datas = pageResult.getValue();
            if (!CollectionUtils.isEmpty(datas)) {
                for (Wx48NewsLogDTO data : datas) {
                    Wx48NewsLogVO logVO = BeanConv.copy(data, Wx48NewsLogVO.class);
                    logVO.setJobTime(DateUtils.formatNewFormat(data.getJobTime()));
                    logVO.setSendEndTime(DateUtils.formatNewFormat(data.getSendEndTime()));
                    logVO.setSendStartTime(DateUtils.formatNewFormat(data.getSendStartTime()));
                    logVO.setHeadPicUrl(adminProperties.getImgproxy() + data.getHeadPicUrl());
                    logVOS.add(logVO);
                }
            }
        }
        return PageViewBuilder.build(logVOS, pageResult.getPage(), pageResult.getRows(), pageResult.getTotalRows());
    }

    @Override
    public Result<Boolean> sendPre(Wx48NewsSendPreRequest request) {
        WxUserInfoSendSingle48HRequest sendSingleRequest = new WxUserInfoSendSingle48HRequest();
        sendSingleRequest.setNewsId(request.getNewsId());
        sendSingleRequest.setAppId(request.getAppId());
        sendSingleRequest.setOpenid(request.getOpenid());
        BaseResult baseResult = wxUserInfoService.sendSingleUserWx48H(sendSingleRequest);
        if (RpcResultCheckUtil.isSuccess(baseResult)) {
            return JsonResultBuilder.succ(true);
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }

    @Override
    public Result<Boolean> cancel(Wx48NewsCancelRequest request) {
        Wx48NewsLogCancelRequest cancelRequest = new Wx48NewsLogCancelRequest();
        cancelRequest.setId(request.getId());
        BaseResult baseResult = wx48NewsInfoService.cancelNewsLog(cancelRequest);
        if (RpcResultCheckUtil.isSuccess(baseResult)) {
            return JsonResultBuilder.succ(true);
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }

    @Override
    public Wx48NewsInfoVO querySpecificReply(String appId) {
        Wx48NewsInfoVO wx48NewsInfoVO = new Wx48NewsInfoVO();
        AppRequest request = new AppRequest();
        request.setAppId(appId);
        SimpleResult<Wx48NewsInfoDTO> simpleResult = wx48NewsInfoService.querySpecificReply(request);
        if (RpcResultCheckUtil.isSuccess(simpleResult)) {
            Wx48NewsInfoDTO newsInfoDTO = simpleResult.getData();
            if (Objects.nonNull(newsInfoDTO)) {
                wx48NewsInfoVO.setId(newsInfoDTO.getId());
                wx48NewsInfoVO.setUseType(newsInfoDTO.getUseType());
                String xmlContent = newsInfoDTO.getXmlContent();
                NewsMessage newsMessage = JSON.parseObject(xmlContent, NewsMessage.class);
                NewsMessage.News news = newsMessage.getNews();
                List<Article> articles = news.getArticles();
                List<Wx48NewsInfo> newsInfos = Lists.newArrayList();
                if (!CollectionUtils.isEmpty(articles)) {
                    for (Article article : articles) {
                        Wx48NewsInfo newsInfo = new Wx48NewsInfo();
                        newsInfo.setTitle(article.getTitle());
                        newsInfo.setImgurl(adminProperties.getImgproxy() + article.getPicurl());
                        newsInfo.setUrl(article.getUrl());
                        newsInfo.setGmtCreate(DateUtils.formatNoSecondFormat(newsInfoDTO.getGmtCreate()));
                        newsInfo.setGmtModified(DateUtils.formatNoSecondFormat(newsInfoDTO.getGmtModified()));
                        newsInfos.add(newsInfo);
                    }
                }
                wx48NewsInfoVO.setNewsInfos(newsInfos);
                return wx48NewsInfoVO;
            }
        }
        return null;
    }
}
